package com.suriya.thirukural;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Random;

import android.app.PendingIntent;
import android.app.Service;
import android.appwidget.AppWidgetManager;
import android.content.Intent;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.IBinder;
import android.util.Log;
import android.widget.RemoteViews;

import com.suriya.thirukural.ThirukuralContext.WidgetInfo;

public class KuralWidgetService extends Service
{

    private ThirukuralContext _context;

    @Override
    public void onCreate()
    {
        super.onCreate();
        _context = (ThirukuralContext) getApplication();
        _context.init();
    }

    @Override
    public IBinder onBind(Intent arg0)
    {
        return null;
    }

    @Override
    public void onStart(Intent intent, int startId)
    {
        super.onStart(intent, startId);
        String command = intent.getStringExtra("command");

        if(command.equals("deleteWidgetIds"))
        {
            int ids[] = intent.getIntArrayExtra("ids");

            for(int id : ids)
            {
                _context.removeWidget(id);
            }
        }
        else if(command.equals("updateWidgets"))
        {
            int ids[] = intent.getIntArrayExtra("ids");

            for(int id : ids)
            {
                Integer curr = Integer.valueOf(id);
                _updateWidget(curr);
            }
        }
        else if(command.equals("updateAllWidgets"))
        {
            _updateAllWidget();
        }

        stopSelf(startId);

    }

    private void _updateAllWidget()
    {
        for(Integer widgetId : _context.widgets.keySet())
        {
            _updateWidget(widgetId);
        }
    }

    private void _updateWidget(Integer curr)
    {
        AppWidgetManager mgr = AppWidgetManager.getInstance(this);
        RemoteViews view = buildRemoteView(_context, _context.widgets.get(curr), curr);
        mgr.updateAppWidget(curr, view);
    }

    public static RemoteViews buildRemoteView(ThirukuralContext context, WidgetInfo widgetInfo, Integer widgetId)
    {
        Log.d("Suriya", "Building kural widget.");

        if(widgetInfo == null) return new RemoteViews(context.getPackageName(), R.layout.kural_appwidget);

        RemoteViews views = null;

        if(widgetInfo.background == false)
        {
            views = new RemoteViews(context.getPackageName(), R.layout.kural_appwidget);
        }
        else
        {
            views = new RemoteViews(context.getPackageName(), R.layout.kural_appwidget_bg);
        }

        int count = 0;
        for(int section : widgetInfo.kuralTopics)
        {
            int sub[] = ThirukuralContext.kuralCount[section];
            for(int curr : sub)
            {
                count += curr;
            }
        }
        count *= 10;

        Log.d("Suriya", "Total KuralCount:" + count);

        Random rand = new Random(System.currentTimeMillis());
        int selection = rand.nextInt(count);

        Log.d("Suriya", "Selected is:" + selection);
        int kuralNum = (selection % 10) + 1;
        selection /= 10;

        int sections[] = new int[3];

        count = 0;
        boolean found = false;

        for(int section : widgetInfo.kuralTopics)
        {
            sections[0] = section + 1;

            int sub[] = ThirukuralContext.kuralCount[section];
            int idx = 1;
            for(int curr : sub)
            {
                sections[1] = idx;
                idx++;

                count += curr;

                if(count > selection)
                {
                    sections[2] = selection - (count - curr) + 1;
                    found = true;
                    break;
                }
            }

            if(found)
            {
                break;
            }
        }

        String sectionStr = "sections";

        for(int currSection : sections)
        {
            sectionStr += ("/" + currSection);
        }
        String kuralFile = sectionStr + "/kural.png";

        Log.d("Suriya", "Kural File:" + kuralFile);
        Log.d("Suriya", "Kural num:" + kuralNum);

        AssetManager assetManager = context.getAssets();
        try
        {
            InputStream stream = assetManager.open(kuralFile);
            BufferedInputStream bis = new BufferedInputStream(stream);
            Bitmap kuralBm = BitmapFactory.decodeStream(bis);
            bis.close();
            stream.close();

            if(kuralBm != null)
            {
                int position = kuralNum - 1;
                Bitmap bm = Bitmap.createBitmap(kuralBm, 0, position * (kuralBm.getHeight() / 10), kuralBm.getWidth(),
                                                kuralBm.getHeight() / 10);
                bm = _trim(bm);
                views.setImageViewBitmap(R.id.kural, bm);
            }
        }
        catch(IOException e)
        {
            e.printStackTrace();
        }

        for(int curr : sections)
        {
            Log.d("Suriya", "Section:" + curr);
        }
        Intent intent = new Intent(context, KuralView.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setData(Uri.withAppendedPath(Uri.parse("thirukural://widget/id/"), "" + widgetId));
        intent.putExtra("section", sections);
        intent.putExtra("depth", 10);
        intent.putExtra("kuralNum", kuralNum);
        PendingIntent pIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        views.setOnClickPendingIntent(R.id.kural, pIntent);
        views.setOnClickPendingIntent(R.id.img, pIntent);

        return views;
    }

    private static Bitmap _trim(Bitmap bm)
    {
        return bm;
    }
}
